
import mapcanvas from '../script/canvas/mapcanvas.js'
import LXCOM from '../script/canvas/common/common.js'
import { LGXEnums } from '../script/canvas/common/sysenum'



class LGXCanvas {
    constructor(canvasID, canvasManager, symbolDefData, canvasWidth, canvasHeight) {
        let canvas = document.getElementById(canvasID);
        this.name = canvasID;
        this.canvas = canvas;

        var style = window.getComputedStyle(canvas, null);
        this.borderLeft = parseFloat(style["border-left-width"]);
        this.borderTop = parseFloat(style["border-top-width"]);
        this.paddingLeft = parseFloat(style["padding-left"]);
        this.paddingTop = parseFloat(style["padding-top"]);

        this.screenWidth = canvasWidth;
        this.screenHeight = canvasHeight;
        var wid = canvasWidth;
        var hgt = canvasHeight;

        this.screenWidth = window.innerWidth;
        this.screenHeight = window.innerHeight;
        var wid = window.innerWidth;
        var hgt = window.innerHeight;

        this.canvasWinWidth = canvasWidth;
        this.canvasWinHeight = canvasHeight;

        var worldMapRect = new LXCOM.LGXRect(0, hgt, wid, 0);//世界坐标系范围，右手坐标系，Z轴朝屏幕外面
        var map = canvas.getContext("2d", { willReadFrequently: true });
        let mapCanvasPtr = new mapcanvas.MapCanvas(canvas, map, wid, hgt, worldMapRect, "viso");

        var rect = canvas.getBoundingClientRect();
        let screenLeft = rect.left + this.borderLeft + this.paddingLeft;
        let screenTop = rect.top + this.borderTop + this.paddingTop;
        mapCanvasPtr.resetMapScreenPos(screenLeft, screenTop, rect.right, rect.bottom);
        mapCanvasPtr.name = canvasID;
        mapCanvasPtr.appendListner(canvasManager);
        console.log("system initial *******************************");
        mapCanvasPtr.initialSymbol2MemFromStore(symbolDefData);
        this.mainctl = mapCanvasPtr;
        this.mainctl.forbidMouseMove = false;


        this.preDragoverPt = { x: 0, y: 0 };
        this.isHovering = false;
        this.preMousePt = { x: 0, y: 0 };
        this.hoveringTimer = null;
        this.LButtonDown = false;

        this.initEvents(canvas);

        canvas.oncontextmenu = function (event) {
            console.log("canvas.oncontextmenu---------------");
            return false;//屏蔽浏览器自带的右键菜单
        };

        canvas.ondblclick = function (event) {
            console.log("canvas.ondblclick---------------");
            return false;//屏蔽浏览器自带的双击菜单
        };

        canvas.ondrop = this.ondrop.bind(this);
        canvas.ondragenter = this.ondragenter.bind(this);
        canvas.ondragover = this.ondragover.bind(this);
    }

    initEvents(canvas) {
        canvas.addEventListener('mousedown', this.onMouseDown.bind(this), false);
        canvas.addEventListener('mouseup', this.onMouseUp.bind(this), false);
        canvas.addEventListener('mousemove', this.onMouseMove.bind(this), false);
        canvas.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
        canvas.addEventListener('dblclick', this.onDBlClick.bind(this), false);        
        canvas.addEventListener('mouseenter', this.onMouseEnter.bind(this), false);    
        canvas.addEventListener('mouseleave', this.onMouseLeave.bind(this), false);    
    }

    onMouseEnter(event){
        console.log("mouse enter canvas**********************");
        let ele = document.getElementById("cmdinpuArea");
        if (ele) {
            ele.focus();
            ele.addEventListener("keydown", window.keyInputFunction);
        }
        else {
            this.canvas.focus();
        }
    }

    onMouseLeave(event){
        console.log("mouse leave canvas**********************");
        let ele = document.getElementById("cmdinpuArea");
        if (ele) {
            ele.blur();
            ele.removeEventListener("keydown", window.keyInputFunction);
        }
    }

    ondragenter(event) {
        event.preventDefault(); // 阻止dragover事件的默认行为
        // console.log("canvas.ondragenter  ");
        console.log(event);
        var mospos = this.getMouseXY(event);
        this.preDragoverPt.x = 0;
        this.preDragoverPt.y = 0;
        console.log(mospos);
        // mainctl.actToolDragEvent(mospos, "enter");

        // 获取拖拽的坐标
        var x = event.clientX;
        var y = event.clientY;

        // 创建自定义的mousemove事件
        var mousemoveEvent = new MouseEvent('mousedown', {
            clientX: x,
            clientY: y,
            bubbles: true,
            cancelable: true,
            button: 0,
            buttons: 1
        });

        // 分发自定义的mousemove事件
        // canvas.dispatchEvent(mousemoveEvent);
        return false;
    }

    ondragover(event) {
        event.preventDefault(); // 阻止dragover事件的默认行为
        // 获取拖拽的坐标
        var x = event.clientX;
        var y = event.clientY;

        // 创建自定义的mousemove事件
        var mousemoveEvent = new MouseEvent('mousemove', {
            clientX: x,
            clientY: y,
            bubbles: true,
            cancelable: true,
            buttons: 1
        });

        // 分发自定义的mousemove事件
        // canvas.dispatchEvent(mousemoveEvent);
        return false;
    }

    ondrop(event) {
        event.preventDefault(); // 阻止dragover事件的默认行为
        // 获取拖拽的坐标
        console.log("mouse ondrop");
        var x = event.clientX;
        var y = event.clientY;

        // 创建自定义的mousemove事件
        var mousemoveEvent = new MouseEvent('mouseup', {
            clientX: x,
            clientY: y,
            bubbles: true,
            cancelable: true,
            button: 0,
            buttons: 0
        });

        // 分发自定义的mousemove事件
        // canvas.dispatchEvent(mousemoveEvent);
        var mospos = this.getMouseXY(event);
        this.mainctl.actToolDragEvent(mospos, "enter");
        return false;
    }

    onMouseDown(evt) {
        this.isHovering = false;
        this.LButtonDown = true;
        var rect = this.canvas.getBoundingClientRect();
        let screenLeft = rect.left + this.borderLeft + this.paddingLeft;
        let screenTop = rect.top + this.borderTop + this.paddingTop;
        this.mainctl.resetMapScreenPos(screenLeft, screenTop, rect.right, rect.bottom);

        console.log("mouse down");
        console.log(evt);
        window.autoFocus2CmdInputArea = true;
        var mousEvt = this.getCustMouseEvent(evt);
        var mospos = this.getMouseXY(evt);
        var clickRightHtml = document.getElementById("clickRightMenu");
        clickRightHtml.style.display = "none";
        let canvasTextEditArea = document.getElementsByClassName('canvasTextBox')[0];
        if (canvasTextEditArea) {
            canvasTextEditArea.style.display = "none";
        }

        console.log(mousEvt, mospos);
        this.mainctl.act2Mouse(mousEvt, mospos);
        this.displayMapInfo(mospos);
        let ele = document.getElementById("cmdinpuArea");
        if (ele) {
            ele.focus();
            ele.addEventListener("keydown", window.keyInputFunction);
        }
        else {
            this.canvas.focus();
        }

        this.mainctl.forbidMouseMove = false;
    }

    onMouseUp(e) {
        this.isHovering = false;
        this.LButtonDown = false;
        var mousEvt = this.getCustMouseEvent(e);
        var mospos = this.getMouseXY(e);
        this.mainctl.act2Mouse(mousEvt, mospos);
    } 

    onMouseWheel(evt) {
        this.isHovering = false;
        evt.preventDefault();
        var e = evt || window.event;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        var mospos = this.getMouseXY(evt);
        this.mainctl.act2MouseWheel(delta, mospos, evt.ctrlKey);
        return false;
    }

    onDBlClick(evt) {
        var mousEvt = this.getCustMouseEvent(evt);
        var mospos = this.getMouseXY(evt);
        console.log("mouse onDBlClick---", mospos);
        this.mainctl.act2Mouse(mousEvt, mospos);
        return false;
    }

    getCustMouseEvent(mosEvnt) {
        var button = mosEvnt.button;
        var type = mosEvnt.type;
        var shiftDown = mosEvnt.shiftKey;
        var altDown = mosEvnt.altKey;
        var ctrlDown = mosEvnt.ctrlKey;
        var buttonDown = mosEvnt.buttons;
        var clientX = mosEvnt.clientX;
        var clientY = mosEvnt.clientY;
        var screenX = mosEvnt.screenX;
        var screenY = mosEvnt.screenY;

        if (button == 0 && buttonDown == 1 && type == "mousedown") {
            type = LGXEnums.LGXMouseMode.LMouseDown;
        }
        else if (buttonDown == 0 && button == 0 && type == "mouseup") {
            type = LGXEnums.LGXMouseMode.LMouseUp;
        }
        else if (buttonDown == 0 && button == 2 && type == "mouseup") {
            type = LGXEnums.LGXMouseMode.RMouseUp;
        }
        else if (buttonDown > 0 && button == 2 && type == "mousedown") {
            type = LGXEnums.LGXMouseMode.RMouseDown;
        }
        else if (type == "dblclick") {
            type = LGXEnums.LGXMouseMode.LMouseDbClick;
        } else if (type == "mousemove" && buttonDown > 0 && button == 0) {
            // console.log("lmousedrag:" + mosEvnt);
            type = LGXEnums.LGXMouseMode.mouseDrag;
        } else if (type == "mousemove") {
            type = LGXEnums.LGXMouseMode.mouseMove;
        }
        return { button, type, shiftDown, altDown, ctrlDown, clientX, clientY, screenX, screenY };
    } 

    getMouseXY(evt) {
        var x = evt.offsetX;
        var y = evt.offsetY;
        var rect = this.canvas.getBoundingClientRect();
        let x1 = rect.left + this.borderLeft + this.paddingLeft;
        let x2 = rect.top + this.borderTop + this.paddingTop;
        this.preMousePt.x = x;
        this.preMousePt.y = y;
        return { x, y }
    }

    displayMapInfo(mospos) {
        var mapSelInfo = this.mainctl.m_pGetDataINTF.getMapSelInfo(mospos);
        var msg = "id=" + mapSelInfo.gid +
            " ,s=" + mapSelInfo.scaling.toFixed(2) +
            " ,sx=" + mapSelInfo.sx.toFixed(2) +
            " ,sy=" + mapSelInfo.sy.toFixed(2) +
            " ,x=" + mapSelInfo.wx.toFixed(2) +
            " ,y=" + mapSelInfo.wy.toFixed(2);
        var statusBar = document.getElementById("statusbar");
        statusBar.innerHTML = msg;
    }

    onReSize() {
        let canvas = document.getElementById(this.name);
        var style = window.getComputedStyle(canvas, null);
        this.borderLeft = parseFloat(style["border-left-width"]);
        this.borderTop = parseFloat(style["border-top-width"]);
        this.paddingLeft = parseFloat(style["padding-left"]);
        this.paddingTop = parseFloat(style["padding-top"]);

        var rect = canvas.getBoundingClientRect();
        let screenLeft = rect.left + borderLeft + paddingLeft;
        let screenTop = rect.top + borderTop + paddingTop;
        this.mainctl.resetMapScreenPos(screenLeft, screenTop, rect.right, rect.bottom);
    }

    onMouseMove(evt) {
        // console.log("onMouseMove ****************");
        //  console.log(evt);
        this.isHovering = false;
        if (!this.mainctl.forbidMouseMove) {
            var mousEvt = this.getCustMouseEvent(evt);
            var mospos = this.getMouseXY(evt);
            this.mainctl.act2Mouse(mousEvt, mospos);
            this.displayMapInfo(mospos);
        }

        if (this.hoveringTimer) {
            clearTimeout(this.hoveringTimer); // 清除之前的定时器
        }

        if (!this.LButtonDown) {
            let that = this;
            this.hoveringTimer = setTimeout(function () {
                // console.log("hoveringTimer ****************");
                // 这里是鼠标悬停时执行的操作
                var mouseX = evt.offsetX;
                var mouseY = evt.offsetY;
                // 判断鼠标位置是否在 Canvas 内部
                let detax = mouseX - that.preMousePt.x;
                let detay = mouseY - that.preMousePt.y;
                let dis = Math.sqrt(detax * detax + detay * detay);
                if (dis < 5) {
                    // console.log('Mouse hovering over the canvas at (' + mouseX + ', ' + mouseY + ')');
                    // 这里可以添加其他你想要执行的操作，比如根据鼠标位置绘制内容等
                    that.mainctl.actToMouseHover(that.preMousePt);
                }
            }, 300); // 设置一个定时器来检测鼠标悬停
        }
    }

    
}

export { LGXCanvas }
